/**
 * 竞品列表页面逻辑
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */

// 清理可能存在的旧实例
if (typeof competitorList !== 'undefined' && competitorList.table) {
    try {
        competitorList.table.destroy();
        $('#competitorTable').empty();
    } catch (e) {
        console.log('清理旧竞品列表实例:', e);
    }
}

var competitorList = {
    
    // DataTable实例
    table: null,
    
    // 当前查看的竞品ID
    currentCompetitorId: null,
    
    /**
     * 初始化
     */
    init() {
        this.initTable();
        this.bindEvents();
        this.loadOurProductList();
    },
    
    /**
     * 加载我方产品列表（用于筛选）
     */
    async loadOurProductList() {
        try {
            const res = await productApi.getList({ page: 1, size: 1000, isOurProduct: 1, status: 1 });
            const products = res.data.list || [];
            
            const select = $('#searchOurProductId');
            select.html('<option value="">按我方产品筛选</option>');
            products.forEach(p => {
                select.append(`<option value="${p.productId}">${p.productName}${p.brand ? ' - ' + p.brand : ''}</option>`);
            });
        } catch (error) {
            console.error('加载我方产品列表失败:', error);
        }
    },
    
    /**
     * 初始化表格
     */
    initTable() {
        this.table = $('#competitorTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: (data, callback, settings) => {
                this.loadCompetitors(data, callback);
            },
            columns: [
                { 
                    data: 'productId',
                    className: 'text-center'
                },
                { 
                    data: 'productName',
                    render: function(data) {
                        return `<strong>${utils.escapeHtml(data)}</strong>`;
                    }
                },
                { 
                    data: 'brand',
                    className: 'text-center',
                    render: function(data) {
                        return data || '-';
                    }
                },
                { 
                    data: 'category',
                    className: 'text-center',
                    render: function(data) {
                        return data ? `<span class="badge bg-info">${data}</span>` : '-';
                    }
                },
                { 
                    data: 'priceRange',
                    className: 'text-center',
                    render: function(data) {
                        return data || '-';
                    }
                },
                { 
                    data: 'competitorLevel',
                    className: 'text-center',
                    render: function(data) {
                        const levelMap = {
                            'direct': '<span class="badge bg-danger">直接竞品</span>',
                            'indirect': '<span class="badge bg-warning">间接竞品</span>',
                            'potential': '<span class="badge bg-info">潜在竞品</span>'
                        };
                        return levelMap[data] || '-';
                    }
                },
                { 
                    data: 'focusLevel',
                    className: 'text-center',
                    render: function(data) {
                        const levelMap = {
                            'high': '<span class="badge bg-danger">重点</span>',
                            'normal': '<span class="badge bg-info">一般</span>',
                            'low': '<span class="badge bg-secondary">低</span>'
                        };
                        return levelMap[data] || '-';
                    }
                },
                { 
                    data: 'productId',
                    className: 'text-center',
                    render: function(data, type, row) {
                        return `<a href="#" onclick="competitorList.viewOurProducts(${data}, '${utils.escapeHtml(row.productName)}'); return false;">查看</a>`;
                    }
                },
                { 
                    data: 'status',
                    className: 'text-center',
                    render: function(data) {
                        const statusClass = utils.getStatusClass(data);
                        const statusText = utils.getStatusText(data);
                        return `<span class="badge bg-${statusClass}">${statusText}</span>`;
                    }
                },
                { 
                    data: 'createTime',
                    className: 'text-center',
                    render: function(data) {
                        return utils.formatDate(data);
                    }
                },
                {
                    data: null,
                    orderable: false,
                    className: 'text-center',
                    render: function(data, type, row) {
                        return `
                            <button class="btn btn-sm btn-primary" onclick="competitorList.edit(${row.productId})" title="编辑">
                                编辑
                            </button>
                            <button class="btn btn-sm btn-info" onclick="competitorList.viewOurProducts(${row.productId}, '${row.productName}')" title="查看被哪些我方产品关注">
                                被关注
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="competitorList.delete(${row.productId})" title="删除">
                                删除
                            </button>
                        `;
                    }
                }
            ],
            language: {
                processing: "处理中...",
                search: "搜索:",
                lengthMenu: "显示 _MENU_ 条",
                info: "显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项",
                infoEmpty: "显示第 0 至 0 项，共 0 项",
                infoFiltered: "(由 _MAX_ 项结果过滤)",
                emptyTable: "暂无数据",
                zeroRecords: "没有找到匹配的数据",
                paginate: {
                    first: "首页",
                    previous: "上页",
                    next: "下页",
                    last: "末页"
                }
            },
            pageLength: API_CONFIG.PAGE_SIZE,
            lengthMenu: API_CONFIG.PAGE_SIZE_OPTIONS.map(size => [size, `${size} 条/页`]),
            order: [[0, 'desc']]
        });
    },
    
    /**
     * 加载竞品数据
     */
    async loadCompetitors(dtData, callback) {
        try {
            const ourProductId = $('#searchOurProductId').val();
            
            let result;
            
            if (ourProductId) {
                // 如果选择了我方产品，查询该产品的竞品列表
                console.log('按我方产品筛选竞品，产品ID:', ourProductId);
                const res = await axios.get(`${API_CONFIG.BASE_URL}/products/${ourProductId}/competitors`);
                const competitors = res.data || [];
                
                // 手动分页
                const page = Math.floor(dtData.start / dtData.length) + 1;
                const size = dtData.length;
                const start = (page - 1) * size;
                const end = start + size;
                
                result = {
                    recordsTotal: competitors.length,
                    recordsFiltered: competitors.length,
                    data: competitors.slice(start, end)
                };
            } else {
                // 否则查询所有竞品
                const params = {
                    page: Math.floor(dtData.start / dtData.length) + 1,
                    size: dtData.length,
                    keyword: $('#searchKeyword').val(),
                    category: $('#searchCategory').val(),
                    isOurProduct: 0,
                    status: $('#searchStatus').val()
                };
                
                const res = await productApi.getList(params);
                
                result = {
                    recordsTotal: res.data.total,
                    recordsFiltered: res.data.total,
                    data: res.data.list
                };
            }
            
            callback(result);
            
        } catch (error) {
            console.error('加载竞品数据失败:', error);
            callback({ recordsTotal: 0, recordsFiltered: 0, data: [] });
        }
    },
    
    /**
     * 绑定事件
     */
    bindEvents() {
        // 搜索框回车
        $('#searchKeyword').on('keypress', function(e) {
            if (e.which === 13) {
                competitorList.search();
            }
        });
        
        // 我方产品筛选变化时自动刷新
        $('#searchOurProductId').on('change', function() {
            competitorList.search();
        });
    },
    
    /**
     * 搜索
     */
    search() {
        this.table.ajax.reload();
    },
    
    /**
     * 重置搜索
     */
    reset() {
        $('#searchKeyword').val('');
        $('#searchCategory').val('');
        $('#searchOurProductId').val('');
        $('#searchStatus').val('');
        this.table.ajax.reload();
    },
    
    /**
     * 显示添加对话框
     */
    showAddDialog() {
        $('#competitorFormModal .modal-title').text('添加竞品');
        $('#competitorForm')[0].reset();
        $('#competitorId').val('');
        $('#competitorLevel').val('direct');
        $('#competitorFocusLevel').val('normal');
        $('#competitorProductStatus').val('on_sale');
        $('#competitorStatus').val('1');
        
        new bootstrap.Modal('#competitorFormModal').show();
    },
    
    /**
     * 编辑
     */
    async edit(id) {
        try {
            utils.showLoading('加载中...');
            const res = await productApi.getById(id);
            utils.hideLoading();
            
            const competitor = res.data;
            
            // 填充表单
            $('#competitorFormModal .modal-title').text('编辑竞品');
            $('#competitorId').val(competitor.productId);
            $('#competitorName').val(competitor.productName);
            $('#competitorBrand').val(competitor.brand || '');
            $('#competitorModel').val(competitor.model || '');
            $('#competitorCategory').val(competitor.category || '');
            $('#competitorPriceRange').val(competitor.priceRange || '');
            $('#competitorLevel').val(competitor.competitorLevel || 'direct');
            $('#competitorFocusLevel').val(competitor.focusLevel || 'normal');
            $('#competitorKeywords').val(competitor.keywords ? competitor.keywords.join(',') : '');
            $('#competitorDescription').val(competitor.description || '');
            $('#competitorProductStatus').val(competitor.productStatus || 'on_sale');
            $('#competitorStatus').val(competitor.status);
            
            new bootstrap.Modal('#competitorFormModal').show();
        } catch (error) {
            utils.hideLoading();
            console.error('加载竞品失败：', error);
        }
    },
    
    /**
     * 保存
     */
    async save() {
        const id = $('#competitorId').val();
        
        // 获取表单数据
        const data = {
            productName: $('#competitorName').val().trim(),
            brand: $('#competitorBrand').val().trim(),
            model: $('#competitorModel').val().trim(),
            category: $('#competitorCategory').val(),
            priceRange: $('#competitorPriceRange').val().trim(),
            isOurProduct: 0,  // 固定为竞品
            competitorLevel: $('#competitorLevel').val(),
            focusLevel: $('#competitorFocusLevel').val(),
            keywords: utils.stringToArray($('#competitorKeywords').val()),
            description: $('#competitorDescription').val().trim(),
            productStatus: $('#competitorProductStatus').val(),
            status: parseInt($('#competitorStatus').val())
        };
        
        // 表单验证
        if (!data.productName) {
            utils.error('请输入产品名称');
            return;
        }
        
        try {
            utils.showLoading('保存中...');
            
            if (id) {
                // 更新
                await productApi.update(id, data);
            } else {
                // 创建
                await productApi.create(data);
            }
            
            utils.hideLoading();
            utils.success('保存成功');
            
            // 关闭对话框
            bootstrap.Modal.getInstance('#competitorFormModal').hide();
            
            // 刷新表格
            this.table.ajax.reload();
            
        } catch (error) {
            utils.hideLoading();
            console.error('保存竞品失败：', error);
        }
    },
    
    /**
     * 删除
     */
    async delete(id) {
        const confirmed = await utils.confirm('确定要删除这个竞品吗？', '删除确认');
        if (!confirmed) return;
        
        try {
            utils.showLoading('删除中...');
            await productApi.delete(id);
            utils.hideLoading();
            
            utils.success('删除成功');
            this.table.ajax.reload();
            
        } catch (error) {
            utils.hideLoading();
            console.error('删除竞品失败：', error);
        }
    },
    
    /**
     * 查看竞争的我方产品（反向查询）
     */
    async viewOurProducts(competitorId, competitorName) {
        this.currentCompetitorId = competitorId;
        
        try {
            utils.showLoading('加载中...');
            
            // 调用反向查询API
            const res = await axios.get(`${API_CONFIG.BASE_URL}/products/competitor/${competitorId}/our-products`);
            console.log('被关注API响应:', res);
            console.log('被关注数据:', res.data);
            
            // 修复：API返回结构是 { code, message, data: [产品列表] }
            const ourProducts = res.data || [];
            console.log('我方产品列表:', ourProducts);
            
            utils.hideLoading();
            
            // 显示竞品名称
            $('#competitorProductName').text(competitorName);
            
            // 渲染我方产品列表
            const container = $('#ourProductsListBody');
            container.empty();
            
            if (!ourProducts || ourProducts.length === 0) {
                container.html('<div class="alert alert-info">暂无我方产品关注该竞品</div>');
            } else {
                const tableHtml = `
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>我方产品</th>
                                <th>品牌</th>
                                <th>竞争类型</th>
                                <th>竞争强度</th>
                                <th>竞争维度</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${ourProducts.map(product => {
                                const typeMap = { 'direct': '直接竞品', 'indirect': '间接竞品', 'potential': '潜在竞品' };
                                const strengthMap = { 'high': '强', 'medium': '中', 'low': '弱' };
                                return `
                                    <tr>
                                        <td><strong>${product.productName}</strong></td>
                                        <td>${product.brand || '-'}</td>
                                        <td><span class="badge bg-danger">${typeMap[product.competitor_type] || product.competitor_type || '-'}</span></td>
                                        <td><span class="badge bg-warning">${strengthMap[product.strength] || product.strength || '-'}</span></td>
                                        <td>${product.dimension || '-'}</td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                `;
                container.html(tableHtml);
            }
            
            // 显示对话框
            new bootstrap.Modal('#ourProductsModal').show();
            
        } catch (error) {
            utils.hideLoading();
            console.error('加载我方产品失败：', error);
            utils.error('加载失败：' + (error.message || '未知错误'));
        }
    },
    
    /**
     * 显示导入对话框
     */
    showImportDialog() {
        Swal.fire({
            title: '批量导入竞品',
            html: `
                <div class="text-start">
                    <input type="file" id="importFile" class="form-control" accept=".xlsx,.xls,.csv">
                    <div class="mt-3">
                        <small class="text-muted">
                            <p>支持Excel（.xlsx, .xls）和CSV格式</p>
                            <p>导入的产品将自动标记为竞品</p>
                        </small>
                    </div>
                </div>
            `,
            width: 600,
            showCancelButton: true,
            confirmButtonText: '开始导入',
            cancelButtonText: '取消',
            preConfirm: () => {
                const fileInput = document.getElementById('importFile');
                const file = fileInput.files[0];
                
                if (!file) {
                    Swal.showValidationMessage('请选择文件');
                    return false;
                }
                
                return file;
            }
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    utils.showLoading('导入中，请稍候...');
                    
                    const res = await productApi.batchImport(result.value);
                    
                    utils.hideLoading();
                    utils.success(`成功导入 ${res.data} 条数据`);
                    
                    // 刷新表格
                    this.table.ajax.reload();
                    
                } catch (error) {
                    utils.hideLoading();
                    console.error('导入失败：', error);
                }
            }
        });
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    // 如果DataTable已存在，先销毁
    if (competitorList.table) {
        try {
            competitorList.table.destroy();
        } catch (e) {
            console.log('销毁旧DataTable:', e);
        }
    }
    competitorList.init();
});

